package com.stox.manager.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.stox.manager.ScripManager;
import com.stox.model.entity.ScripEntity;
import com.stox.repository.ScripRepository;

@Component
@Transactional
public class ScripManagerImpl implements ScripManager {
	private static final String cacheName = "com.stox.model.entity.ScripEntity";
	
	@Autowired
	private ScripRepository scripRepository;

	@Override
	@CachePut(value=cacheName, key="#scrip.code")
	@CacheEvict(value=cacheName, key="#scrip.code.concat('-exists')")
	public ScripEntity saveAndFlush(ScripEntity scrip) {
		return scripRepository.saveAndFlush(scrip);
	}
	
	@Override
	@Cacheable(value=cacheName, key="#root.method.name")
	public List<ScripEntity> findAll() {
		return scripRepository.findAll();
	}
	
	@Cacheable(cacheName)
	public List<ScripEntity> findByExchangeCode(String exchangeCode) {
		return scripRepository.findByExchangeCode(exchangeCode);
	}

	@Override
	@Cacheable(value=cacheName, key="#scripCode.concat('-exists')")
	public boolean exists(String scripCode) {
		return scripRepository.exists(scripCode);
	}
	
	@Override
	@Cacheable(cacheName)
	public ScripEntity findOne(String scripCode) {
		return scripRepository.findOne(scripCode);
	}
	
	@Transactional
	@CachePut(cacheName)
	@CacheEvict(value=cacheName, key="#scrip.code.concat('-exists')")
	public ScripEntity save(ScripEntity scrip) {
		if(!scripRepository.exists(scrip.getCode())){
			return scripRepository.save(scrip);
		}
		return null;
	}

}
